#include <iostream>
#include <vector>
#include <unistd.h>
#include <cassert>
#include <sys/wait.h>
#include <sys/types.h>
#include "mypipe.hpp"
using namespace std;

int gnum = 5;
Task t;

class Point
{
private:
    static int number;

public:
    pid_t c_id;
    int write_fd;
    string pname;

public:
    Point(int id, int fd)
        : c_id(id), write_fd(fd)
    {
        char namebuf[64];
        snprintf(namebuf, sizeof(namebuf), "process-%d[%d:%d]", number++, c_id, write_fd);
        pname = namebuf;
    }
    string name() const
    {
        return pname;
    }
    ~Point()
    {
    }
};
int Point::number = 0;

void WaitOrder()
{
    while (true)
    {

        int order = 0;
        int n = read(0, &order, sizeof(int));

        if (n == sizeof(int))
        {
            t.execute(order);
        }
        else if (n == 0)
        {
            cout << "父进程叫我下班了，我先走了" << getpid() << endl;
            break;
        }
        else
        {

            break;
        }
    }
}

void create(vector<Point> *points)
{
    for (int i = 0; i < gnum; i++)
    {
        // 创建管道
        int myfd[2] = {0};

        int n = pipe(myfd);
        assert(n == 0);
        (void)n; // 不需要就强转一下

        // 创建进程
        pid_t id = fork();
        assert(id != -1);

        if (id == 0) // 子进程写
        {
            // 关闭不需要的fd
            close(myfd[1]);
            dup2(myfd[0], 0); // 将myfd[0]替换掉 文件描述符0 ->重定向

            WaitOrder();
            close(myfd[0]);
            exit(0);
        }

        // 父进程写
        // 1.3关闭不需要的fd
        close(myfd[0]);

        // 将构造好的子进程和他的管道写端，构建对象
        points->push_back(Point(id, myfd[1]));
    }
}
int ShowBoard()
{
    cout << "---------------------------------" << endl;
    cout << "0.执行PRINT任务   1.执行Insert任务" << endl;
    cout << "2.执行POP任务     3.退出          " << endl;
    cout << "---------------------------------" << endl;
    cout << "请选择#";
    int order = 0;
    cin >> order;
    return order;
}
void cltrcreate(vector<Point> &points)
{
    int num = 0;
    int cnt = 0;
    while (true)
    {
        // 1任务选择
        int order = ShowBoard();
        if (order == 3)
            break;
        if (order < 0 || order > 2)
            continue;

        // 2.选择进程
        int index = cnt++;
        cnt %= points.size();
        string name = points[index].name();
        cout << "选择了进程" << name << ":处理进程:" << order << endl;

        write(points[index].write_fd, &order, sizeof(order));
        sleep(1);
    }
}

void waitcreate(vector<Point> &points)
{
    // 需要让子进程全部退出---子需要父进程关闭写端fd
    for (auto &ep : points)
    {
        close(ep.write_fd);
    }
    for (auto &ep : points)
    {
        waitpid(ep.c_id, nullptr, 0);
    }
    cout << "子进程全部下班，父进程任务完成" << endl;
}

int main()
{
    // 父进程写入，子进程读取
    vector<Point> points;
    // 控制子进程
    create(&points);

    // 得到points
    cltrcreate(points);

    // 回收子进程，子进程退出
    waitcreate(points);

    return 0;
}
